$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useBeforeClick,useUpdateRows, useDataIndexChange }) {
    //mstform
    var dgrid1_toolbar = $NG.getCmpApi("toolbar_p_form_impl_labor_chg");
    var dgrid2_toolbar = $NG.getCmpApi("toolbar_p_form_impl_daliy_chg");
    var dgrid3_toolbar = $NG.getCmpApi("toolbar_p_form_impl_sec_dev_chg");
  
    function hiddenInput(table,tabled){
        //来源主键 || 主键
        $NG.updateUI((updater)=>{
          console.log(`过滤参数检查`,updater);
            updater.fieldSetForm[table].u_source_phid.setProps({
                hidden:true
            })
            tabled.forEach(item=>{
                updater.editGrid[item].u_phid.setProps({
                    hidden:true
                })
                updater.editGrid[item].u_source_phid.setProps({
                    hidden:true
                })
            })
            
        })
    }
    hiddenInput("p_form_impl_cost_budget_chg",["p_form_impl_labor_chg","p_form_impl_daliy_chg","p_form_impl_sec_dev_chg"])
    var mstform = $NG.getCmpApi("p_form_impl_cost_budget_chg");
    var dgrid1 = $NG.getCmpApi("p_form_impl_labor_chg"); //实施人工p_form_impl_labor_chg
    var dgrid2 = $NG.getCmpApi("p_form_impl_daliy_chg"); //日常费用p_form_impl_daliy_chg
    var dgrid3 = $NG.getCmpApi("p_form_impl_sec_dev_chg"); //二次开发费用p_form_impl_sec_dev_chg
    const toolbars = [
      // { toolbar: $NG.getCmpApi("toolbar"), items: ["copy", "attachment", "check", "history", "applycheck"] },
      // { toolbar: $NG.getCmpApi("toolbar_top"), items: ["imp", "imp_push", "check", "history", "applycheck"] },
      { toolbar: dgrid1_toolbar, items: [ "attachment"] },
      { toolbar: dgrid2_toolbar, items: [ "attachment"] },
      { toolbar: dgrid3_toolbar, items: [ "attachment"] },
    ];
    let lockTime = 0;
    let saveLock = true
    useBeforeClick(({args})=>{
        const isLock = (data)=>{
            return data.reduce((value,item)=>{
                if(item.checked&&item.u_source_phid){
                    value = false
                }
                return value
            },true)
        }
        console.log(`删除行参数`,args);
        let lock = true
        switch(args[0].containerId){
            case 'p_form_impl_labor_chg':
                const arr1 = dgrid1.getData()
                lock = isLock(arr1)
                break;
            case 'p_form_impl_daliy_chg':
                const arr2 = dgrid2.getData()
                lock = isLock(arr2)
                break
            case 'p_form_impl_sec_dev_chg':
                const arr3 = dgrid3.getData()
                lock = isLock(arr3)
                break
        }
        if(!lock){
            $NG.alert("不能删除已存在关联记录的数据，只能删除当前表单新增数据！")
        }
        return lock
    },"deleterow")
    if(page.oType == 'add'||page.oType == 'edit'){
        console.log('表检查',mstform);
        lockTime = setInterval(()=>{
    var mstform = $NG.getCmpApi("p_form_impl_cost_budget_chg");
            if(mstform.getItem("u_source_phid").getValue()){
                $NG.execServer("getIsImpSSInfo",{source:mstform.getItem("u_source_phid").getValue()},(res)=>{
                    console.log(`引用结果`,res);
                    if(res.count == 0) return 
                    const _data = JSON.parse(res.data)[0].extendObjects
                    if(_data.app_status == "1"){
                        return 
                    }
                    saveLock = false
                    $NG.alert("当前预算费用已被设备清单引用请停止变更！！！")
                })
                clearInterval(lockTime)
            }
        },1000)
    }
  // 设置默认值人民币和汇率
  if(page.oType=='add'){
  $NG.updateState((updater)=>{
      updater.data.p_form_impl_cost_budget_chg.setProps({
          phid_fcur:{
              label:'人民币',
              value:1
          },
          exchangerate:1
      })
  })
  }
    //生成phid
    function generate15DigitNumber(arr) {
        arr.forEach((item) => {
      let str = "";
      // 获取当前时间戳
      let timestamp = Date.now().toString();
      // 如果时间戳不足 15 位，计算需要补充的位数
      let remainingLength = 15 - timestamp.length;
      if (remainingLength > 0) {
        // 生成指定长度的随机数
        let randomPart = "";
        for (let i = 0; i < remainingLength; i++) {
          randomPart += Math.floor(Math.random() * 10);
        }
        // 将时间戳和随机数拼接成 15 位数字
        str = String(timestamp + randomPart);
      } else {
        // 如果时间戳长度超过 15 位，截取前 15 位
        str = String(timestamp.slice(0, 15));
      }
            console.log(str);
      if (!item.u_phid) {
        item.u_phid = str;
        dgrid1.refreshView();
        dgrid2.refreshView();
        dgrid3.refreshView();
      }
    });
    }
  
    useBeforeClick(({args})=>{
        if(!saveLock){
            $NG.alert("当前预算费用已被设备清单引用请停止变更！！！")
            return false
        }
        return true
    },"save")
    useBeforeClick(({args})=>{
        if(!saveLock){
            $NG.alert("当前预算费用已被设备清单引用请停止变更！！！")
            return false
        }
        return true
    },"check")
    toolbars.forEach(({ toolbar, items }) => {
      if (toolbar) {
        items
          .map((item) => toolbar.getItem(item)) // 提前获取所有按钮
          .filter(Boolean) // 过滤掉不存在的按钮
          .forEach((toolbarItem) => toolbarItem.setHidden()); // 隐藏按钮
      }
    });
    //实施人工
    useUpdateRows(({ args }) => {
        caculatedgrid();
        generate15DigitNumber(args[0])
        reduceNum()
      }, "p_form_impl_labor_chg");
      //实施日常
      useUpdateRows(({ args }) => {
        caculatedgrid();
        generate15DigitNumber(args[0])
        reduceNum()
      }, "p_form_impl_daliy_chg");
      //实施二开
      useUpdateRows(({ args }) => {
        caculatedgrid();
        generate15DigitNumber(args[0])
        reduceNum()
      }, "p_form_impl_sec_dev_chg");
    dgrid1_toolbar.insert({
      id: "dgrid1ShowUI",
      text: "显示原预算数据",
      iconCls: "icon-New",
    });
    dgrid1_toolbar.insert({
      id: "dgrid1hideUI",
      text: "隐藏原预算数据",
      iconCls: "icon-New",
    });
    dgrid2_toolbar.insert({
      id: "dgrid2ShowUI",
      text: "显示原预算数据",
      iconCls: "icon-New",
    });
    dgrid2_toolbar.insert({
      id: "dgrid2hideUI",
      text: "隐藏原预算数据",
      iconCls: "icon-New",
    });
  
    useClick(() => {
      dgrid1ShowUI();
    }, "dgrid1ShowUI");
    useClick(() => {
      dgrid1hideUI();
    }, "dgrid1hideUI");
  
    useClick(() => {
      dgrid2ShowUI();
    }, "dgrid2ShowUI");
    useClick(() => {
      dgrid2hideUI();
    }, "dgrid2hideUI");
  
    ////////////////////////////////////////////////////////////--mstform
  
    if (mstform) {
      getPtInfoByPhid();
      cntMFilter();
      getCntCount("p_form_impl_cost_budget_chg", "u_cnt", function () {
        getCntMInfoByPhid();
      });
      if (page.oType == "add") {
        dgridAdd();
        mstform.getItem("bill_name").setValue(mstform.getItem("phid_pc").getText() || "" + "实施费用预算变更单");
        useValuesChange(({ args }) => {
          mstform.getItem("bill_name").setValue(mstform.getItem("phid_pc").getText() || "" + "实施费用预算变更单");
        }, "p_form_impl_cost_budget_chg.phid_pc");
      }
    } else {
      console.error("mstform is not available");
    }
  
    useValuesChange(({ args }) => {
      cntMFilter();
      getPtInfoByPhid();
      $NG.updateState((updater) => {
        updater.data.p_form_impl_cost_budget_chg.setProps({
          u_pc_no: args[0].phid_pc.PhId,
          u_cnt: { label: "", value: "" },
          u_cnt_no: "",
        });
      });
      //单一合同自动带出
      getCntCount("p_form_impl_cost_budget_chg", "u_cnt", function () {
        getCntMInfoByPhid();
        dgridAdd();
      });
    }, "p_form_impl_cost_budget_chg.phid_pc");
    useValuesChange(({ args }) => {
      getCntMInfoByPhid();
      dgridAdd();
    }, "p_form_impl_cost_budget_chg.u_cnt");
  
    ////////////////////////////////////////////////////////////--dgrid1
    if (dgrid1) {
      $NG.updateUI((updater) => {
        const fields = ["u_source_phid"];
        fields.forEach((field) => {
          updater.editGrid.p_form_impl_labor_chg[field].setProps({
            hidden: true, //隐藏
          });
        });
      });
  
      //差额计算
      function reduceNum(){
        setTimeout(() => {
      const sstotal =
        mstform.getItem("u_total_impl_amt").getValue() -
        mstform.getItem("u_total_impl_amt_ori").getValue();
      const ssrgtotal =
        mstform.getItem("u_total_impl_labor_amt").getValue() -
        mstform.getItem("u_total_impl_labor_amt_ori").getValue();
      const rctotal =
        mstform.getItem("u_total_daily_amt").getValue() -
        mstform.getItem("u_total_daily_amt_ori").getValue();
      const wbtotal =
        mstform.getItem("u_total_sec_dev_amt").getValue() -
        mstform.getItem("u_total_sec_dev_amt_ori").getValue();
      $NG.updateState((updater) => {
        updater.data.p_form_impl_cost_budget_chg.setProps({
          u_total_impl_amt_gap: sstotal,
          u_total_impl_labor_amt_gap: ssrgtotal,
          u_total_daily_amt_gap: rctotal,
          u_total_sec_dev_amt_gap: wbtotal,
        });
      });
    },300);
      }
      
      function dgrid1ShowUI(params) {
        //表体多字段设置属性
        $NG.updateUI((updater) => {
          for (let j = 1; j <= 12; j++) {
            // const _str = `u_man_days_${j < 10 ? "0" + j : j}`;
            const _str_ori = `u_man_days_${j < 10 ? "0" + j : j}_ori`;
            updater.editGrid.p_form_impl_labor_chg[_str_ori].setProps({
              hidden: false, //隐藏
            });
          }
          const fields = ["u_qty_ori", "u_labor_amt_ori"];
          fields.forEach((field) => {
            updater.editGrid.p_form_impl_labor_chg[field].setProps({
              hidden: false, //隐藏
            });
          });
        });
      }
      function dgrid1hideUI(params) {
        //表体多字段设置属性
        $NG.updateUI((updater) => {
          for (let j = 1; j <= 12; j++) {
            // const _str = `u_man_days_${j < 10 ? "0" + j : j}`;
            const _str_ori = `u_man_days_${j < 10 ? "0" + j : j}_ori`;
            updater.editGrid.p_form_impl_labor_chg[_str_ori].setProps({
              hidden: true, //隐藏
            });
          }
          const fields = ["u_qty_ori", "u_labor_amt_ori"];
          fields.forEach((field) => {
            updater.editGrid.p_form_impl_labor_chg[field].setProps({
              hidden: true, //隐藏
            });
          });
        });
      }
    }
    payProjectFilter();
    function payProjectFilter() {
      $NG.updateUI((updater) =>
        updater.editGrid.p_form_impl_daliy_chg.u_expense_code.setProps((p) => {
          return {
            ...p,
            editor: {
              ...p.editor,
              clientSqlFilter: {
                u_sequence: "02",
              },
            },
          };
        })
      );
    }
    useDataIndexChange(({ args, instance }) => {
      var items = args[0];
      if (items.u_position) {
        $NG.execServer("getSimpleDataByPhid", { phid: items.u_position }, function (res) {
          if (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // 尝试将 c_descript 转换为数字
            const personnelRate = Number(datas.c_descript);
            if (isNaN(personnelRate)) {
              // 如果转换失败，可以设置一个默认值或者处理错误
              console.error("Invalid value for u_personnel_rate:", datas.c_descript);
            }
            items.u_personnel_rate = personnelRate;
            caculatedgrid();
          }
          dgrid1.refreshView();
        });
      }
      instance.updateRow(items);
    }, "p_form_impl_labor_chg.u_position");
    ////////////////////////////////////////////////////////////--dgrid2
    if (dgrid2) {
      $NG.updateUI((updater) => {
        const fields = ["u_source_phid"];
        fields.forEach((field) => {
          updater.editGrid.p_form_impl_daliy_chg[field].setProps({
            hidden: true, //隐藏
          });
        });
      });
  
      ////////////////////////////////////////////////////////////--dgrid2 function--////////////////////////////////////////////////////////////
      ////////////////////////////////////////////////////////////--dgrid2 function--////////////////////////////////////////////////////////////
      ////////////////////////////////////////////////////////////--dgrid2 function--////////////////////////////////////////////////////////////
      function dgrid2ShowUI(params) {
        $NG.updateUI((updater) => {
          for (let j = 1; j <= 12; j++) {
            const _str_ori = `u_expenses_${j < 10 ? "0" + j : j}_ori`;
            updater.editGrid.p_form_impl_daliy_chg[_str_ori].setProps({
              hidden: false, //隐藏
            });
          }
          const fields = ["u_annual_impl_amt_ori"];
          fields.forEach((field) => {
            updater.editGrid.p_form_impl_daliy_chg[field].setProps({
              hidden: false, //隐藏
            });
          });
        });
      }
      function dgrid2hideUI(params) {
        $NG.updateUI((updater) => {
          for (let j = 1; j <= 12; j++) {
            const _str_ori = `u_expenses_${j < 10 ? "0" + j : j}_ori`;
            updater.editGrid.p_form_impl_daliy_chg[_str_ori].setProps({
              hidden: true, //隐藏
            });
          }
          const fields = ["u_annual_impl_amt_ori"];
          fields.forEach((field) => {
            updater.editGrid.p_form_impl_daliy_chg[field].setProps({
              hidden: true, //隐藏
            });
          });
        });
      }
    } else {
      console.log("dgrid2 获取失败");
    }
    ////////////////////////////////////////////////////////////--dgrid3
    if (dgrid3) {
  
      $NG.updateUI((updater) => {
        const fields = ["u_source_phid"];
        fields.forEach((field) => {
          updater.editGrid.p_form_impl_sec_dev_chg[field].setProps({
            hidden: true, //隐藏
          });
        });
      });
    } else {
      console.log("dgrid3 获取失败");
    }
    //--mstform function
    function getPtInfoByPhid() {
      if (mstform.getItem("phid_pc").getValue()) {
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          //帮助字段赋值
          $NG.updateState((updater) => {
            updater.data.p_form_impl_cost_budget_chg.setProps({
              u_pc_no: datas.pc_no, //项目编号
              u_agreed_sts_dt: datas.start_date, //计划完工日期
              u_agreed_pcl_dt: datas.end_date, //计划竣工日期
              u_sqgw: {
                //售前顾问
                value: datas.user_sqgw_phid,
                label: datas.user_sqgw_name,
              },
              //事业部
              u_division: {
                value: datas.division_phid,
                label: datas.division_name,
              },
              //大区
              u_region: {
                value: datas.phid_org_phid,
                label: datas.phid_org_name,
              },
              u_regional_center: {
                //区域中心
                value: datas.regional_center_phid,
                label: datas.regional_center_name,
              },
              u_product_line: {
                //产品线
                value: datas.midwife_phid,
                label: datas.midwife_name,
              },
              u_dept: {
                //部门
                value: datas.dept_phid,
                label: datas.dept_name,
              },
              u_pc_type: {
                //项目类型
                value: datas.type_phid,
                label: datas.type_name,
              },
            });
          });
        });
      }
    }
  
    function cntMFilter() {
      $NG.updateUI((updater, state) => {
        updater.fieldSetForm.p_form_impl_cost_budget_chg.u_cnt.setProps({
          onBeforeOpen: async () => {
            var phid_pc = mstform.getItem("phid_pc").getValue();
            if (!phid_pc) {
              $NG.alert("请先选择项目");
              return false;
            } else {
              return true;
            }
          },
          ...(!!mstform.getItem("phid_pc").getValue() && {
            clientSqlFilter: {
              bill_type: 1,
              phid_pc: mstform.getItem("phid_pc").getValue(),
            },
          }),
        });
      });
    }
  
    function getCntMInfoByPhid(params) {
      $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        //帮助字段赋值
        $NG.updateState((updater) => {
          //【注意这里的表名不能为控件ID，必须要是表名】
          updater.data.p_form_impl_cost_budget_chg.setProps({
            u_cnt_no: datas.pcm_no, //合同编码
            u_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同价税合计
            u_invoice_type: {
              //发票类型
              value: datas.invoice_type_phid,
              label: datas.invoice_type_name,
            },
          });
        });
      });
    }
    ////////////////////////////////////////////////////////////--mstform function
  
    function dgridAdd(params) {
      dgrid1.clearRows();
      dgrid2.clearRows();
      dgrid3.clearRows();
      setTimeout(async () => {
        // 赋值
        function _sum(num) {
          $NG.updateState((updater) => {
            updater.data.p_form_impl_cost_budget_chg.setProps({
              u_total_impl_amt_ori: num,
            });
          });
        }
        // 临时存储上一次的费用
        const _countMaps = {
          _d1: 0,
          _d2: 0,
          _d3: 0,
          set d1(value) {
            this._d1 = value;
            _sum(this._d1 + this._d2 + this._d3);
          },
          set d2(value) {
            this._d2 = value;
            _sum(this._d1 + this._d2 + this._d3);
          },
          set d3(value) {
            this._d3 = value;
            _sum(this._d1 + this._d2 + this._d3);
          },
        };
        Object.defineProperties(_countMaps, {
          _d1: {
            configurable: false,
            writable: true,
            enumerable: false,
            value: 0,
          },
          _d2: {
            configurable: false,
            writable: true,
            enumerable: false,
            value: 0,
          },
          _d3: {
            configurable: false,
            writable: true,
            enumerable: false,
            value: 0,
          },
        });
        if (dgrid1) {
          await $NG.execServer("getImplLaborBudgetInfo", { cnt: mstform.getItem("u_cnt").getValue() }, function (res) {
            let _data = null;
            if (typeof res.data === "string") {
              _data = JSON.parse(res.data);
            } else {
              _data = res.data;
            }
            console.log(`测试`, _data);
            //默认增行,批量新增表体数据
            var gridArr = []; //定义表体数组
            var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
            for (var i = 0; i < gridCount; i++) {
              var gridObj = {};
              //对表体字段进行赋值,可以取数据库中的值进行赋值
              const mphid = _data[i].extendObjects.mphid
                if(!mstform.getItem("u_source_phid").getValue()){
                    $NG.updateState((updater)=>{
                        updater.data.p_form_impl_cost_budget_chg.setProps({
                            u_source_phid:mphid
                        })
                    })
                }
              // 年度
              gridObj.u_source_phid = _data[i].extendObjects.phid;
              gridObj.u_year = _data[i].extendObjects.u_year;
              gridObj.u_man_months_ori = _data[i].extendObjects.u_man_months;
              gridObj.u_qty = _data[i].extendObjects.u_qty;
              gridObj.u_qty_ori = _data[i].extendObjects.u_qty;
              gridObj.u_labor_amt_ori = _data[i].extendObjects.u_labor_amt;
              gridObj.u_labor_amt = _data[i].extendObjects.u_labor_amt;
              // 人员岗位
              gridObj.u_position_EXName = _data[i].extendObjects.position_name;
              gridObj.u_position = _data[i].extendObjects.position_phid;
              // 人员费率
              gridObj.u_personnel_rate = _data[i].extendObjects.u_personnel_rate;
              // 人工费合计
              gridObj.u_labor_amt = _data[i].extendObjects.u_labor_amt;
              // 数量
              gridObj.u_qty = _data[i].extendObjects.u_qty;
              // 1- 12 月
              for (let j = 1; j <= 12; j++) {
                const _str = `u_man_days_${j < 10 ? "0" + j : j}`;
                const _str_ori = `u_man_days_${j < 10 ? "0" + j : j}_ori`;
                gridObj[_str] = _data[i].extendObjects[_str];
                gridObj[_str_ori] = _data[i].extendObjects[_str];
              }
              gridArr.push(gridObj);
            }
            //调用新增表体行数据的函数
            let _count_ori = 0;
            let _count = 0;
            gridArr.forEach((item) => {
              _count_ori += item.u_labor_amt_ori;
              _count += item.u_labor_amt;
            });
            $NG.updateState((updater) => {
              _countMaps.d1 = _count;
              updater.data.p_form_impl_cost_budget_chg.setProps({
                u_total_impl_labor_amt_ori: _count_ori,
                u_total_impl_labor_amt: _count,
              });
            });
            dgrid1.addRows(gridArr);
          });
        }
        if (dgrid2) {
          await $NG.execServer("getImplDaliyBudgetInfo", { cnt: mstform.getItem("u_cnt").getValue() }, function (res) {
            let _data = null;
            if (typeof res.data === "string") {
              _data = JSON.parse(res.data);
            } else {
              _data = res.data;
            }
            //默认增行,批量新增表体数据
            var gridArr = []; //定义表体数组
            var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
            for (var i = 0; i < gridCount; i++) {
              //对表体字段进行赋值,可以取数据库中的值进行赋值
              var gridObj = {};
              gridObj.u_source_phid = _data[i].extendObjects.phid;
              gridObj.u_year = _data[i].extendObjects.u_year;
              gridObj.u_annual_impl_amt_ori = _data[i].extendObjects.u_annual_impl_amt;
              gridObj.u_annual_impl_amt = _data[i].extendObjects.u_annual_impl_amt;
              gridObj.u_expense_code = _data[i].extendObjects.u_expense_code;
              gridObj.u_expense_code_EXName = _data[i].extendObjects.u_expense_name;
              gridObj.u_expense_desc = _data[i].extendObjects.u_expense_description;
              // 1- 12 月
              for (let j = 1; j <= 12; j++) {
                const _str = `u_expenses_${j < 10 ? "0" + j : j}`;
                const _str_ori = `u_expenses_${j < 10 ? "0" + j : j}_ori`;
                gridObj[_str] = _data[i].extendObjects[_str];
                gridObj[_str_ori] = _data[i].extendObjects[_str];
              }
              gridArr.push(gridObj);
            }
            let _count_ori = 0;
            let _count = 0;
            gridArr.forEach((item) => {
              _count_ori += item.u_annual_impl_amt_ori;
              _count += item.u_annual_impl_amt;
            });
            $NG.updateState((updater) => {
              _countMaps.d2 = _count;
              updater.data.p_form_impl_cost_budget_chg.setProps({
                u_total_daily_amt_ori: _count_ori,
                u_total_daily_amt: _count,
              });
            });
            //调用新增表体行数据的函数
            dgrid2.addRows(gridArr);
          });
        }
        if (dgrid3) {
          await $NG.execServer(
            "getImplSecDevBudgetInfo",
            {
              cnt: mstform.getItem("u_cnt").getValue(),
            },
            function (res) {
              let _data = null;
              if (typeof res.data === "string") {
                _data = JSON.parse(res.data);
              } else {
                _data = res.data;
              }
              //默认增行,批量新增表体数据
              var gridArr = []; //定义表体数组
              var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
              for (var i = 0; i < gridCount; i++) {
                //对表体字段进行赋值,可以取数据库中的值进行赋值
                var gridObj = {};
                gridObj.u_source_phid = _data[i].extendObjects.phid;
                gridObj.u_sec_dev_sys = _data[i].extendObjects.u_sec_dev_sys;
                gridObj.u_sec_dev_amt = _data[i].extendObjects.u_sec_dev_amt;
                gridObj.u_sec_dev_amt_ori = _data[i].extendObjects.u_sec_dev_amt;
                gridArr.push(gridObj);
              }
              let _count_ori = 0;
              let _count = 0;
              gridArr.forEach((item) => {
                _count_ori += item.u_sec_dev_amt_ori;
                _count += item.u_sec_dev_amt;
              });
              $NG.updateState((updater) => {
                _countMaps.d3 = _count;
                updater.data.p_form_impl_cost_budget_chg.setProps({
                  u_total_sec_dev_amt_ori: _count_ori,
                  u_total_sec_dev_amt: _count,
                });
              });
              //调用新增表体行数据的函数
              dgrid3.addRows(gridArr);
            }
          );
        }
      }, 200);
    }
  
    // 返回当月最大天数
    function getDaysInMonth(year, month) {
      const y = parseInt(year, 10);
      const m = parseInt(month, 10);
      return new Date(y, m, 0).getDate();
    }
  
    function caculatedgrid() {
      let u_total_impl_labor_amt = 0; //实施人工费
      let u_total_daily_amt = 0; //合计日常费用
      let u_total_sec_dev_amt = 0; //合计二次开发费用
      let u_total_impl_amt = 0; //合计总费用
  
      dgrid1.getRows().forEach((items, rowIndex) => {
        let total = 0;
        for (let i = 1; i <= 12; i++) {
          const str = "u_man_days_" + String(i).padStart(2, "0");
          const manDays = Number(items[str]);
          let maxDay = getDaysInMonth(items.u_year, i);
          if (isNaN(manDays)) {
            items[str] = 0;
          } else if (manDays > maxDay) {
            items[str] = 0;
            $NG.alert(`第${rowIndex + 1}行第 ${i}月人天不能超过${maxDay}天`);
          }
          total += Number(items[str] > 21.75 ? 21.75 : items[str]) || 0;
        }
        // 人月=人天/21.75
        // 人工费合计=人员费率*数量*人月
        items.u_man_months = total / 21.75;
        items.u_labor_amt = ((Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_man_months) || 0)).toFixed(2);
        u_total_impl_labor_amt += parseFloat(items.u_labor_amt) || 0;
      });
      dgrid2.getRows().forEach((items) => {
        let total = 0;
        for (let i = 1; i <= 12; i++) {
          const str = "u_expenses_" + String(i).padStart(2, "0");
          total += Number(items[str]) || 0;
        }
        items.u_annual_impl_amt = total;
        u_total_daily_amt += parseFloat(items.u_annual_impl_amt) || 0;
      });
      dgrid3.getRows().forEach((items) => {
        u_total_sec_dev_amt += parseFloat(items.u_sec_dev_amt) || 0;
      });
      dgrid1.refreshView();
      dgrid2.refreshView();
      dgrid3.refreshView();
  
      u_total_impl_amt = u_total_impl_labor_amt + u_total_daily_amt + u_total_sec_dev_amt;
  
      $NG.updateState((updater) => {
        updater.data.p_form_impl_cost_budget_chg.setProps({
          u_total_impl_labor_amt: u_total_impl_labor_amt, //
          u_total_daily_amt: u_total_daily_amt, //
          u_total_sec_dev_amt: u_total_sec_dev_amt, //
          u_total_impl_amt: u_total_impl_amt, //
        });
      });
    }
  
  
  
  
  
  //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
  //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
  //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
  //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
  //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
  
  
  if (page.oType == "add"|| page.oType == "edit") {
  
  
    { //添加按钮
        $NG.getCmpApi('toolbar_p_form_impl_daliy_chg').insert({
            id: "fyadd",
            text: "选择费用项目",
            iconCls: "icon-New"
        });
    }
  }
  useClick(async function ({ args }) {
  
    // 打开帮助选择器并应用过滤条件
    $NG.external.openNGHelp({
        type: "NGMultipleHelp",
        helpId: "cost_pc",
        valueField: "d.phid.",
        labelField: "d.u_name",
        clientSqlFilter: "u_sequence = '02'"  // 应用过滤条件
    }).then((data) => {
        console.log(data);
  
        var gridArr = []; // 初始化 gridArr 数组
        for (var i = 0; i < data.length; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
                u_expense_code: '',
  
            };
            // 对表体字段进行赋值, 可以取数据库中的值进行赋值
            gridObj.u_expense_code = data[i].origin.phid;
            gridObj.u_expense_code_EXName = data[i].origin.u_name;
            // 关键步骤：将 gridObj 添加到 gridArr 数组中
            gridArr.push(gridObj);
        }
        console.log(gridArr); // 确保这里打印出来的 gridArr 不是空的
        dgrid2.addRows(gridArr); // 将数据添加到表格组件中
    });
  }, "fyadd");
  
  
  });
  
  //获取合同数量
  function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
      console.log(res, "count");
      switch (res.count) {
        case 0:
          return;
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects;
          const temp_map = {};
          temp_map[key] = datas.phid;
          temp_map[`${key}_EXName`] = datas.bill_name;
          $NG.updateState((updater) => {
            updater.data[table].setProps({
              ...temp_map,
            });
            setTimeout(() => {
              if (fun) {
                fun();
              }
            }, 200);
          });
      }
    });
  }
  